import { memo, useCallback, useEffect, useMemo, useState } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import {
  Affix,
  Avatar,
  Badge,
  Button,
  Divider,
  Input,
  message,
  notification,
  Spin,
  Tag,
  Tooltip,
} from 'antd';
import { API_BASEURL } from '@/constants/api';
import { resAddOrCancelCollect, resIsCollect } from '@/services/collect';
import { resGoodsCommentList } from '@/services/comment';
import { resGoodsDetail } from '@/services/goods';
import { resOrdersComment } from '@/services/orders';
import { isLoginState } from '@/store/authStore';
import { cartStore, useCartStore } from '@/store/cartStore';
import {
  CommentOutlined,
  HeartFilled,
  HeartOutlined,
  ShopOutlined,
  ShoppingCartOutlined,
} from '@ant-design/icons';
import { useInfiniteScroll, useRequest } from 'ahooks';
import { useRecoilValue } from 'recoil';
import BooksCommentItem from '@/components/BooksCommentItem';
import NoMore from '@/components/NoMore';
import { formatUrl } from '@/utils/format';
import './index.scss';

const GoodsPage: FC<PropsWithChildren<{}>> = () => {
  const params = useParams();
  const { data, refresh } = useRequest(resGoodsDetail, {
    defaultParams: [Number(params.id)],
  });
  const isLogin = useRecoilValue(isLoginState);
  const navigate = useNavigate();
  const location = useLocation();
  const { addCart } = useCartStore();
  const [addLoading, setAddLoading] = useState(false);
  const onAddCartHandler = useCallback(() => {
    if (!isLogin) {
      message.warn('请先登录').then(() => {
        navigate(`/login?redirect=${location.pathname}`);
      });
      return;
    }
    setAddLoading(true);
    addCart({ id: Number(params.id), num: 1 }).then(() => {
      setAddLoading(false);
      notification.success({
        message: '添加购物车成功!',
        description: (
          <div>
            <div>《{data?.title}》已经添加到您的购物车</div>
            <div className={'indent-2 mt-1'}> 请前往购物车查看！</div>
          </div>
        ),
        duration: 10,
        top: 75,
      });
    });
    refresh();
  }, [isLogin, data]);

  const {
    data: commentData,
    loading: commentLoading,
    reload,
    loadMore,
    loadingMore,
    noMore,
  } = useInfiniteScroll<API.PaginationResult<API.CommentStruct>>(
    (currentData) => {
      return resGoodsCommentList(Number(params.id), {
        pageSize: 10,
        current: Math.ceil(currentData?.list.length! / 10 || 0) + 1,
      });
    },
    {
      target: document,
      isNoMore: (d) => {
        return !d || d?.list.length >= d?.total;
      },
      threshold: 200,
    }
  );

  const [comment, setComment] = useState('');
  const onCommentClick = useCallback(() => {
    comment &&
      resOrdersComment(1, {
        goods_id: Number(params.id),
        content: comment,
      }).then(() => {
        setComment('');
        reload();
        message.success('发送书评成功！');
      });
  }, [comment]);

  const carts = useRecoilValue(cartStore);
  const isDisable = useMemo(() => {
    return (
      data?.stock === 0 ||
      carts.find((value) => value.goods_id === Number(params.id))?.num! >=
        data?.stock!
    );
  }, [carts, data]);

  const htmlDetails = { __html: data?.details || '' };

  const {
    run,
    data: isCollect,
    refresh: collectRefresh,
  } = useRequest(resIsCollect, { manual: true });

  const { runAsync: runCollect, loading: collectLoading } = useRequest(
    resAddOrCancelCollect,
    { manual: true }
  );

  useEffect(() => {
    data && run(data.id);
  }, [data]);

  return (
    <div className={'w-[1200px] space-y-16 p-16 m-auto min-h-screen'}>
      <div className={'bg-cover rounded-lg'}>
        <div className={'flex items-center rounded-lg space-x-16 '}>
          <div className={'rounded-lg bg-white flex-1 '}>
            {data ? (
              <div>
                <div className={'flex justify-center items-center pt-10 '}>
                  <div className={''}>
                    {data && data.user ? (
                      <div
                        className={
                          'flex justify-around items-center flex-col h-48'
                        }
                      >
                        <Tag
                          color={'#2db7f5'}
                          icon={<ShopOutlined />}
                          className={'ant-tag-cus'}
                        >
                          <span className={'text-base font-serif'}>商 家</span>
                        </Tag>
                        <div className={''}>
                          <Avatar
                            className={'cursor-pointer'}
                            size={55}
                            src={API_BASEURL + '/' + data.user.avatar}
                            alt="avatar"
                            onClick={() => {
                              navigate('/user_page/' + data.user_id);
                            }}
                          />
                        </div>
                        <div
                          className={' text-center cursor-pointer'}
                          onClick={() => {
                            navigate('/user_page/' + data.user_id);
                          }}
                        >
                          <Tag color={'blue'} className={'ant-tag-cus'}>
                            <span className={'text-lg font-serif'}>
                              {data.user.name}
                            </span>
                          </Tag>
                        </div>
                      </div>
                    ) : null}
                  </div>
                  <div className={'flex-justify-items-center ml-32 '}>
                    <img
                      className={'w-32 rounded-lg h-48'}
                      src={formatUrl(data.cover)}
                      alt=""
                    />
                    <div className={'py-8 px-16 space-y-3'}>
                      <div className={'text-lg truncate'}>{data.title}</div>
                      <div className={'truncate'}>{data.description}</div>
                      <div className={'truncate'}>{data.category.name}</div>
                      <div className={'space-x-2'}>
                        <strong className={'text-blue-700 text-lg'}>
                          <em className={'text-xs px-0.5'}>￥</em>
                          {data.price * data.discount}
                        </strong>
                        {data.discount < 1 ? (
                          <i className={'line-through text-gray-600'}>
                            <em className={'text-xs px-0.5'}>￥</em>
                            {data.price}
                          </i>
                        ) : null}
                      </div>
                    </div>
                  </div>
                </div>
                <Divider>书籍介绍</Divider>
                <div
                  className={'px-12 text-sm text-gray-600 leading-6 indent-8'}
                  dangerouslySetInnerHTML={htmlDetails}
                />
                <Divider />
                <div className={'pb-6 px-10 space-x-4 text-right'}>
                  <Button
                    loading={collectLoading}
                    onClick={() => {
                      runCollect(data.id).then(() => {
                        message.success(
                          isCollect?.is_check === 1
                            ? '取消收藏成功'
                            : '收藏成功'
                        );
                        collectRefresh();
                      });
                    }}
                    icon={
                      isCollect?.is_check === 1 ? (
                        <HeartFilled />
                      ) : (
                        <HeartOutlined />
                      )
                    }
                  />
                  <Button
                    icon={<ShoppingCartOutlined />}
                    type={'primary'}
                    onClick={onAddCartHandler}
                    loading={addLoading}
                    disabled={isDisable}
                  >
                    {!isDisable
                      ? '加入购物车'
                      : data.stock === 0
                      ? '商品无货'
                      : '购物车数量已到商品上限'}
                  </Button>
                </div>
              </div>
            ) : null}
          </div>
        </div>
      </div>
      <div className={'p-16 bg-white rounded-lg'}>
        <div className={'rounded-lg bg-blue-50  p-8 pb-16 '}>
          <Badge.Ribbon
            placement={'start'}
            text={<span className={'  font-serif px-2'}>经典书评</span>}
          >
            <Badge.Ribbon
              text={<span className={'  font-serif px-2'}>买家回复</span>}
            >
              <div
                className={
                  'py-2.5 bg-white rounded-lg shadow text-lg text-center font-serif'
                }
              >
                <Tag color={'green'}>
                  <span className={'text-lg  font-serif px-2'}>经典书评</span>
                  <strong className={'text-lg  font-serif px-2'}>&</strong>
                  <span className={'text-lg  font-serif px-2'}>买家回复</span>
                </Tag>
              </div>
            </Badge.Ribbon>
          </Badge.Ribbon>
          <Spin spinning={commentLoading} />
          {commentData && commentData.list.length > 0 ? (
            <div className={'pt-8 px-4'}>
              {commentData.list.map((value) => (
                <BooksCommentItem data={value} key={value.id} />
              ))}
            </div>
          ) : null}
          <NoMore loadingMore={loadingMore} noMore={noMore} />
        </div>
      </div>
      <Affix offsetBottom={40}>
        <div className={'flex-justify-items-center'}>
          <div
            className={
              'flex-justify-items-center bg-blue-300/80 rounded-full shadow-lg pl-4'
            }
          >
            <div className={'w-[600px]'}>
              <Input.TextArea
                placeholder="可以发布自己对这本书的感想哦！"
                autoSize
                value={comment}
                onChange={(e) => {
                  setComment(() => {
                    return e.target.value;
                  });
                }}
                maxLength={10000}
              />
            </div>
            <Tooltip title={'发表书评'}>
              <Button
                shape="circle"
                icon={<CommentOutlined />}
                size={'large'}
                className={'ml-2'}
                onClick={onCommentClick}
              />
            </Tooltip>
          </div>
        </div>
      </Affix>
    </div>
  );
};

export default memo(GoodsPage);
